﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Net.Mime;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace ZhaoXi.Http.Client
{
    /// <summary>
    /// HttpWebRequestHelper的封装
    /// </summary>
    public class HttpWebRequestHelper
    {
        #region Get请求封装
        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public HttpWebResponse Get(string url, Dictionary<string, string>? headers)
        {
            return Request(url, MethodType.Get, 100000, headers);
        }

        /// <summary>
        /// Get只有Url地址
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public HttpWebResponse Get(string url)
        {
            return this.Get(url, null);
        }
        #endregion

        #region Post请求封装

        /// <summary>
        ///  Post请求
        ///  1.可能带有头信息
        ///  2.带有Json格式传值的对象
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentJson"></param>
        /// <returns></returns>
        public HttpWebResponse Post(string url, string? contentJson, Dictionary<string, string>? headers = null)
        {
            return Request(url, MethodType.Post, 100000, headers, "application/json", null, contentJson);
        }

        /// <summary>
        /// 只有Url地址和头信息的Post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public HttpWebResponse Post(string url, Dictionary<string, string>? headers = null)
        {
            return Request(url, MethodType.Post, 100000, headers, "application/json", null, null);
        }

        /// <summary>
        /// 表单提交
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        public HttpWebResponse Post(string url, Dictionary<string, string>? form, Dictionary<string, string>? headers = null)
        {
            return Request(url, MethodType.Post, 100000, headers, "application/x-www-form-urlencoded", form, null);
        }

        #endregion

        /// <summary>
        /// 大而全的函数基本包含了所有的场景
        /// </summary>
        /// <param name="url">请求的URL地址</param>
        /// <param name="methodType">请求的类型：Get Post Put Delete</param>
        /// <param name="timeOut">超时时间</param>
        /// <param name="headers">头信息</param>
        /// <param name="contentType">contentType</param> 
        /// <param name="form">表单提交的信息</param>
        /// <param name="contentJson">Body Json提交的信息--必须是被Json序列化的字符串</param>
        /// <returns></returns>
        private HttpWebResponse Request(string url, MethodType methodType, int timeOut, Dictionary<string, string>? headers = null, string? contentType = null,
            Dictionary<string, string>? form = null, string? contentJson = null)
        {
            //创建一个HttpWebRequest
            HttpWebRequest webRequest = WebRequest.CreateHttp(url) as HttpWebRequest;
            //设置请求的类型Get Post  Put Delete
            webRequest.Method = methodType.ToString();
            //设置超时时间
            webRequest.Timeout = timeOut;
            //设置contentType
            webRequest.ContentType = contentType;
            //设置头信息
            if (headers != null)
            {
                foreach (var item in headers)
                {
                    webRequest.Headers.Add(item.Key, item.Value);
                }
            }

            //设置表单提交数据 
            if (form != null)
            {
                string postData = string.Empty;
                foreach (var item in form)
                {
                    postData = postData + $"&{item.Key}={item.Value}";
                }
                postData = postData.TrimStart();
                using (StreamWriter writer = new StreamWriter(webRequest.GetRequestStream()))
                {
                    writer.Write(postData);
                }
            }

            //设置JSON格式传值的方式
            if (contentJson != null)
            {
                using (StreamWriter writer = new StreamWriter(webRequest.GetRequestStream()))
                {
                    writer.Write(contentJson);
                }
            }

            try
            {
                //开始发起请求
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                return response;

            }
            catch (WebException ex) // 捕获网络异常处理错误情况，例如404, 500等HTTP错误状态码。
            {
                HttpWebResponse response = (HttpWebResponse)ex.Response;
                return response; 
            }
        }
    }

    public enum MethodType
    {
        Get,
        Post,
        Put,
        Delete
    }

    public static class HttpReponseExtension
    {
        public static string ReponseToString(this HttpWebResponse response)
        {
            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                string responseText = reader.ReadToEnd(); // 获取响应内容为字符串形式
                response.Dispose(); 
                return responseText;
            }
        }
    }


}